mod utils;
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::fs;
use std::net::TcpStream;
use utils::db;
use utils::db::Db;
use utils::web_server;

fn main() {
    match web_server::_read_yaml("src/config.yaml") {
        Ok(config) => {
            let mut server = web_server::WebServer::new(config["port"].as_str());

            server.get("/home", home_handler);
            server.get("/", about_handler);
            server.listen();
        }
        Err(e) => eprintln!("读取配置文件时出错: {}", e),
    }
}
fn home_handler(stream: &mut std::net::TcpStream, ctx: &mut web_server::WebServer) {
    let file_content = fs::read_to_string("src/output.txt").expect("Error reading file");
    let mut data = HashMap::new();
    data.insert("content".to_string(), file_content);
    ctx.success_json(stream, &data);
}
#[derive(Debug, mysql::prelude::FromRow, Serialize)]
struct User {
    id: u32,
    name: String,
}
fn about_handler(stream: &mut TcpStream, ctx: &mut web_server::WebServer) {
    let mut db = Db::new(db::DbConfig {
        host: "127.0.0.1".to_string(),
        port: 3306,
        db_name: "fiber".to_string(),
        user: "root".to_string(),
        pass: "".to_string(),
    });

    // 执行查询并处理结果
    let query = "SELECT id, name FROM users";
    match db.query_generic::<User>(query) {
        Ok(users) => {
            ctx.success(stream, &serde_json::to_string(&users).unwrap());
        }
        Err(e) => {
            eprintln!("查询失败: {}", e);
        }
    }
}
